package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiNiuUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author: Eric
 * @since: 2020/11/24
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    private static final Logger log = LoggerFactory.getLogger(SetmealController.class);

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 套餐图片上传
     * @param imgFile
     * @return
     */
    @PostMapping("/upload")
    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    public Result upload(MultipartFile imgFile){
        //- 获取文件名，获取它的后缀名
        String originalFilename = imgFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //- 产生唯一名称，拼接后缀名， 图片名
        String imgName = UUID.randomUUID().toString() + suffix;
        //- 调用QiNiuUtils上传
        try {
            QiNiuUtils.uploadViaByte(imgFile.getBytes(),imgName);
            //- 成功后返回图片名和域名
            //{
            //    	imgName: 图片名
            //    	domain: 域名
            //	}
            Map<String,String> resultMap = new HashMap<String,String>();
            resultMap.put("imgName",imgName);
            resultMap.put("domain",QiNiuUtils.DOMAIN);

            return new Result(true, MessageConstant.UPLOAD_SUCCESS,resultMap);
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("上传文件失败",e);
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    /**
     * 添加套餐
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    public Result add(@Validated @RequestBody Setmeal setmeal, Integer[] checkgroupIds){
        // 调用服务添加
        Integer setmealId = setmealService.add(setmeal,checkgroupIds);
        // 生成静态页面
        Jedis jedis = jedisPool.getResource();
        String key = "setmeal:static:html";
        jedis.sadd(key, setmealId+"|1|" + System.currentTimeMillis());
        jedis.close();
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    /**
     * 分页查询
     */
    @PostMapping("/findPage")
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult<Setmeal> pageResult = setmealService.findPage(queryPageBean);
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,pageResult);
    }

    /**
     * 通过id查询
     */
    @GetMapping("/findById")
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    public Result findById(int id){
        Setmeal setmeal = setmealService.findById(id);
        /**
         * Result{
         *     flag:
         *     message;
         *     data:{
         *     	domain: 路径
         *     	setmeal: formData  img图片名
         *        }
         * }
         */
        Map<String,Object> resultMap = new HashMap<String,Object>(2);
        resultMap.put("domain",QiNiuUtils.DOMAIN);
        resultMap.put("setmeal",setmeal);
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,resultMap);
    }

    /**
     * 通过套餐id查询选中的检查组id集合
     */
    @GetMapping("/findCheckgroupIdsBySetmealId")
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    public Result findCheckgroupIdsBySetmealId(int id){
        List<Integer> ids = setmealService.findCheckgroupIdsBySetmealId(id);
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,ids);
    }

    /**
     * 更新套餐
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('SETMEAL_EDIT')")
    public Result update(@Validated@RequestBody Setmeal setmeal, Integer[] checkgroupIds){
        // 调用服务更新
        setmealService.update(setmeal,checkgroupIds);
        Jedis jedis = jedisPool.getResource();
        String key = "setmeal:static:html";
        jedis.sadd(key, setmeal.getId()+"|1|" + System.currentTimeMillis());
        jedis.close();
        return new Result(true, "更新套餐成功");
    }

    /**
     * 通过id删除
     */
    @PostMapping("/deleteById")
    @PreAuthorize("hasAuthority('SETMEAL_DELETE')")
    public Result deleteById(int id){
        // 调用服务删除
        setmealService.deleteById(id);
        Jedis jedis = jedisPool.getResource();
        String key = "setmeal:static:html";
        jedis.sadd(key, id+"|0|" + System.currentTimeMillis());
        jedis.close();
        return new Result(true, "删除套餐成功");
    }

}
